
 /**
 * MimeMailManagerImpl.java.java.
 * User: BrianChen Date: 2012-6-20 下午09:33:28
 *
 * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
 * All rights reserved.
 */
package com.collapsar.core.email.impl;

import java.io.File;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.collapsar.core.email.IMimeMailManager;
import com.collapsar.core.template.ITemplateFormatter;

/**
 * <pre>
 * REVISIONS: 
 * Version 	Date 		Author 			Description
 * ------------------------------------------------------------------- 
 * 1.0 		2012-6-20 	BrianChen 	1. Created this class. 
 * </pre>
 * 
 * @author BrianChen
 * @date 2012-6-20 下午09:33:28
 * @version 1.0
 * @see
 * MIME邮件服务类
 * MimeMailFormatter由velocity/freemaker引擎生成的的html格式邮件, 并带有附件.
 */
public class MimeMailManagerImpl implements IMimeMailManager{
	private static Logger logger = LoggerFactory.getLogger(MimeMailManagerImpl.class);
	private static final String ENCODING ="utf-8";
	
	private JavaMailSender mailSender = null;
	private ITemplateFormatter mimeMailFormatter = null;
	

	
	@Override
	public void sendNotificationMail(String to, String from, String subject,
			String classPathTemplate, Map<String, Object> templateContext)
			throws Exception {
		MimeMessage htmlMsg = this.mailSender.createMimeMessage();
		try{
			MimeMessageHelper helper = new MimeMessageHelper(htmlMsg, true, ENCODING);
			helper.setTo(to);
			helper.setFrom(from);
			helper.setSubject(subject);
			helper.setText(this.mimeMailFormatter.formatEmailEntry(classPathTemplate, templateContext), true);
			File attachment = (File)templateContext.get("attachement");
			this.buildAttachement(helper, attachment);
			this.mailSender.send(htmlMsg);
			logger.info("HTML版邮件已发送至："+to);
		}catch(Exception ex){
			logger.error("发送邮件失败", ex);
			throw ex;
		}
	}
	
	/**
	 * 添加附件
	 * @param helper
	 * @param attachment
	 * @throws MessagingException
	 */
	private void buildAttachement(MimeMessageHelper helper, File attachment) throws MessagingException{
		if(attachment != null){
			helper.addAttachment(attachment.getName(), attachment);
		}
	}

	@Override
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	@Override
	public void setMimeMailFormatter(ITemplateFormatter mimeMailFormatter) {
		this.mimeMailFormatter = mimeMailFormatter;
	}

}

